package net.sppan.blog.store;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sppan.blog.model.Offer;
import net.sppan.blog.model.OfferUser;
import net.sppan.blog.utils.ObjectUtils;

public class OfferStore {

	private Map<String, List<Offer>> mapping = new HashMap<>();
	private Map<String, List<String>> idMapping = new HashMap<>();
	private Map<String, Offer> offerMap = new HashMap<>();

	private OfferStore() {

	}

	private static class OfferStoreHold {
		private final static OfferStore offerSotre = new OfferStore();
	}

	public static OfferStore getInstance() {
		return OfferStoreHold.offerSotre;
	}

	public void init() {
		//加载所有offer数据
		List<Offer> offers = Offer.dao.find("select * from sys_offer where status=?", "published");
		//加载user和offer关系数据
		List<OfferUser> ous = OfferUser.dao.getAllList();
		//构建user和offer的对应关系
		if (offers == null ) {
			offers = new ArrayList<>();
		}
		if(ous == null) {
			ous = new ArrayList<>();
		}
		build(ous, offers);
	}

	private void build(List<OfferUser> ous, List<Offer> offers) {
		Map<String, Offer> tmap = new HashMap<>();
		Map<String, List<Offer>> _mapping = new HashMap<>();
		Map<String, List<String>> _idMapping = new HashMap<>();
		for (Offer offer : offers) {
			tmap.put(offer.getId().toString(), offer);
		}
		for (OfferUser ou : ous) {
			String offerId = ou.getOfferId().toString();
			Offer o = tmap.get(offerId);
			if (o == null) {
				continue;
			}
			String userId = ou.getUser();
			List<Offer> innerList = _mapping.get(userId);
			List<String> idList = _idMapping.get(userId);
			if (innerList == null) {
				innerList = new ArrayList<>();
				idList = new ArrayList<>();
			}
			innerList.add(o);
			idList.add(o.getId().toString());
			_idMapping.put(userId, idList);
			_mapping.put(userId, innerList);
		}
		this.mapping = _mapping;
		this.idMapping = _idMapping;
		this.offerMap = tmap;
	}

	public List<Offer> getOffers(String userId) {
		return mapping.get(userId);
	}

	public List<String> getOfferIdss(String userId) {
		return idMapping.get(userId);
	}

	public Offer getOfferById(String offerId) {
		return offerMap.get(offerId);
	}

}
